<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Oauth extends CI_Controller {

    private   $TB ;
    private   $WB ;
    private   $data ;
    private   $wb_akey ;
    private   $wb_skey ;
    private   $wb_callback_url ;
    private   $tb_akey ;
    private   $tb_skey ;


    function __construct() {
        parent::__construct();
        $this->load->model('user_model');
        $this->load->library('Taobao/TopSdk');
        $this->TB = new TopClient;
        $this->TB->appkey = $this->config->item('tb_akey');
        $this->TB->secretKey = $this->config->item('tb_skey');
        $this->tb_akey = $this->config->item('tb_akey');
        $this->tb_skey = $this->config->item('tb_skey');
        include_once(LIBPATH.'/WbOAuth.php');
        $this->wb_akey = $this->config->item('wb_akey');
        $this->wb_skey = $this->config->item('wb_skey');
        $this->wb_callback_url = $this->config->item('wb_callback_url');
        $this->WB = new WbOAuth($this->wb_akey,$this->wb_skey);
        $this->WB->debug = 0;

    }

    public function wb_oauth()
    {
        $this->data['oauth_url'] =  $this->WB->getAuthorizeURL($this->wb_callback_url);
        $this->load->view('oauth/index',$this->data);
    }

    public function wb_callback()
    {
        if (isset($_REQUEST['code'])) {
            $keys = array();
            $keys['code'] = $_REQUEST['code'];
            $keys['redirect_uri'] = $this->wb_callback_url;
            try {
                $token = $this->object->getAccessToken( 'code', $keys ) ;
            } catch (OAuthException $e) {

            }
        }
        if(isset($token)&&!empty($token)) {

            $this->session->sess_expiration = $token['expires_in'];
            $this->session->set_userdata('token',$token['access_token']);
            $this->session->set_userdata('uid',$token['uid']);
            $this->session->set_userdata('remind_in',$token['remind_in']);
            $this->session->set_userdata('expires_in',$token['expires_in']);
        }

        redirect(site_url('index/index'));

    }


    public function tb_oauth()
    {
         $url = 'https://oauth.taobao.com/authorize';
         $params = array(
            'response_type'=>'code',
            'client_id'=>$this->tb_akey,
            'redirect_uri'=>site_url('oauth/tb_callback')
        );
        $params_string = http_build_query($params);
        redirect($url.'?'.$params_string);
    }

    public function tb_callback()
    {
        $url = 'https://oauth.taobao.com/token';
        $postfields= array(
            'grant_type'=>'authorization_code',
            'client_id'=>$this->tb_akey,
            'client_secret'=>$this->tb_skey,
            'code'=>$this->input->get_post('code'),
            'redirect_uri'=>site_url('taobao/callback')
        );
        $token = json_decode($this->TB->curl($url,$postfields));
        if(isset($token)&&!empty($token))
        {
            $result = $this->user_model->get_row(array('tuid'=>$token->taobao_user_id));
            if(!empty($result))
            {
                if($token->access_token!==$result['token'])
                {
                    $data['token'] = $token->access_token;
                    $data['last_login_time'] = date('Y-m-d H:i:s',time());
                    $data['last_login_ip']   =   get_client_ip();
                    $this->user_model->edit_row($data,array('tuid'=>$token->taobao_user_id));
                }

                $this->session->sess_expiration = $token->expires_in;
                $this->session->set_userdata('token',$token->access_token);
                $this->session->set_userdata('taobao_user_id',$token->taobao_user_id);
                $this->session->set_userdata('tb_is_login',1);
                $this->session->set_userdata('tb_nick',$result['nick']);

            }
            else
            {
                $user_info = $this->tb_user_info($token->access_token);
                $data['nick'] = $user_info['nick']?$user_info['nick']:'nick';
                $data['token'] = $token->access_token;
                $data['tuid'] = $token->taobao_user_id;
                $data['last_login_time'] = date('Y-m-d H:i:s',time());
                $data['last_login_ip']   =   get_client_ip();
                $this->user_model->add_row($data);
                $this->session->sess_expiration = $token->expires_in;
                $this->session->set_userdata('token',$token->access_token);
                $this->session->set_userdata('taobao_user_id',$token->taobao_user_id);
                $this->session->set_userdata('tb_is_login',1);
                $this->session->set_userdata('tb_nick',$user_info['nick']);
            }
        }
        redirect('admin/index') ;
    }



    public function tb_user_info($token)
    {
        $req = new UserSellerGetRequest;
        $req->setFields("nick,sex");
        $resp = _object_array($this->TB->execute($req,$token));
        if(isset($resp['user'])&&!empty($resp['user']))
        {
            return   $resp['user'] ;
        }
        return false;
    }








}